/**
 * 自定义时间选择组件，支持周选择以及季度选择
 * by LHC
 * create 2020-06-19
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, Tooltip, message, Row, Col, Select } from 'antd';
import moment from 'moment';
import { FormItemLayout, NoLableLayout } from '../formPub';
import styles from './style.less';

const yearFormat = 'YYYY';
const Option = Select.Option;
let theme = '';
class SimpleQuarterC extends Component {
  state = {
    isopen: false,
    time: null,
    year: '',
    quarters: [
      {
        key: '1',
        label: '第一季度',
      },
      {
        key: '2',
        label: '第二季度',
      },
      {
        key: '3',
        label: '第三季度',
      },
      {
        key: '4',
        label: '第四季度',
      },
    ],
  };
  // props默认值
  static defaultProps = {
    title: '',
    placeholder: '请选择年份',
    helper: '',
    onRef: () => {}, // 本组件的引用
    labalWrap: false, // 默认title不换行
    highCurrentDate: true, // true---年份选择需晚于limitYear年份，false-----年份选择需早于limitYear年份
    limitYear: '2022', // 限制的年份
    formItemLayout: FormItemLayout, // 布局
    disabled: false,
  };

  componentDidMount() {
    // 父组件对本组件的引用
    this.props.onRef(this);
  }

  // 非初始化状态下更改时间(供父组件调用)
  // 需传入{yearKey:"2019",quarterKey:"1"}格式的参数
  // 其中年份必传，1,2,3,4,"",分别对应一季度，二季度，三季度，四季度，和不设置季度。
  setDate = (value) => {
    const valueF = {};
    valueF[this.props.dataIndex] = value;
    this.props.form.setFieldsValue(value);
    if (value['quarter']) {
      this.handleQuarterChange(value['quarter']);
    }
  };

  // 禁选日期设定
  disabledDate = (current) => {
    let year = current.format('YYYY');
    return year > moment().endOf('year').format('YYYY');
  };
  //年份选择
  handlePanelChange = (value) => {
    let that = this;
    if (!this.props.highCurrentDate && parseInt(this.props.limitYear) < parseInt(value.format(yearFormat))) {
      message.error(`时间选择不得晚于${this.props.limitYear}年！`);
      that.setState({
        isopen: false,
      });
      return;
    }
    if (this.props.highCurrentDate && parseInt(this.props.limitYear) > parseInt(value.format(yearFormat))) {
      message.error(`时间选择不得早于${this.props.limitYear}年！`);
      that.setState({
        isopen: false,
      });
      return;
    }
    const { yearKey, quarterKey, dateBeginKey, dateEndKey } = that.props;
    if (!value) {
      o[yearKey] = '';
      o[dateBeginKey] = '';
      o[dateEndKey] = '';
      that.props.form.setFieldsValue(o);
      that.setState({
        time: value,
        year: value.format(yearFormat),
        isopen: false,
      });
      return;
    }
    let beginDate = '';
    let endDate = '';
    let year = value.format('YYYY') + '-';
    let quarter = this.props.form.getFieldValue(quarterKey) ? this.props.form.getFieldValue(quarterKey) : '-';
    if (quarter == 1) {
      beginDate = '01-01';
      endDate = '03-31';
    } else if (quarter == 2) {
      beginDate = '04-01';
      endDate = '06-30';
    } else if (quarter == 3) {
      beginDate = '07-01';
      endDate = '09-30';
    } else if (quarter == 4) {
      beginDate = '10-01';
      endDate = '12-31';
    }
    let o = {};
    o[yearKey] = value;
    o[dateBeginKey] = year + beginDate;
    o[dateEndKey] = year + endDate;
    that.props.form.setFieldsValue(o);
    if (quarter != '-') {
      that.props.onQuarterChange({ beginDate: year + beginDate + ' 00:00:00', endDate: year + endDate + ' 23:59:59' });
    } else {
      that.props.onQuarterChange({ beginDate: '', endDate: '', lackDate: true });
    }
    that.setState({
      time: value,
      year: value.format(yearFormat),
      isopen: false,
    });
  };
  //年份开关
  handleOpenChange = (status) => {
    if (status) {
      this.setState({ isopen: true });
    } else {
      this.setState({ isopen: false });
    }
  };
  //清除
  clearTime = (v1, v2) => {
    const { yearKey, quarterKey, dateBeginKey, dateEndKey } = this.props;
    let o = {};
    o[quarterKey] = '';
    o[dateBeginKey] = '';
    o[dateEndKey] = '';
    this.props.form.setFieldsValue(o);
    this.props.onQuarterChange({ beginDate: '', endDate: '' });
    this.setState({
      time: null,
      year: '',
    });
  };
  //季度发生变化时调用
  handleQuarterChange = (v1, v2) => {
    let that = this;
    const { yearKey, quarterKey, dateBeginKey, dateEndKey } = that.props;
    if (!v1) {
      let o = {};
      o[quarterKey] = '';
      o[dateBeginKey] = '';
      o[dateEndKey] = '';
      that.props.form.setFieldsValue(o);
      that.props.onQuarterChange({ beginDate: '', endDate: '', lackDate: true });
      return;
    }
    let beginDate = '';
    let endDate = '';
    let year = this.props.form.getFieldValue(yearKey) ? moment(this.props.form.getFieldValue(yearKey)).format('YYYY') + '-' : '-';
    if (v1 == 1) {
      beginDate = '01-01';
      endDate = '03-31';
    } else if (v1 == 2) {
      beginDate = '04-01';
      endDate = '06-30';
    } else if (v1 == 3) {
      beginDate = '07-01';
      endDate = '09-30';
    } else if (v1 == 4) {
      beginDate = '10-01';
      endDate = '12-31';
    }
    let o = {};
    o[quarterKey] = v1;
    o[dateBeginKey] = year + beginDate;
    o[dateEndKey] = year + endDate;
    that.props.form.setFieldsValue(o);
    that.props.onQuarterChange({ beginDate: year + beginDate + ' 00:00:00', endDate: year + endDate + ' 23:59:59' });
  };
  render() {
    const {
      formItemLayout,
      labalWrap,
      helper,
      title,
      form,
      quarterKey,
      yearKey,
      initialValueYear,
      initialValueQuarter,
      placeholder,
      dateBeginKey,
      dateEndKey,
      style,
      rules,
      disabled,
    } = this.props;
    const { getFieldDecorator } = form;
    const { isopen } = this.state;
    let quarters = [
      {
        key: '1',
        label: '第一季度',
      },
      {
        key: '2',
        label: '第二季度',
      },
      {
        key: '3',
        label: '第三季度',
      },
      {
        key: '4',
        label: '第四季度',
      },
    ];
    return (
      <Form.Item
        className={labalWrap ? 'labalWrap' : ''}
        labelCol={title ? formItemLayout.labelCol : NoLableLayout.labelCol}
        wrapperCol={title ? formItemLayout.wrapperCol : NoLableLayout.wrapperCol}
        style={style}
        label={
          title ? (
            helper ? (
              <span>
                {title}&nbsp;
                <Tooltip title={helper}>
                  <QuestionCircleOutlined />
                </Tooltip>
              </span>
            ) : (
              <span>{title}</span>
            )
          ) : undefined
        }
      >
        <Row>
          <Col style={{ display: 'flex' }}>
            {/* {getFieldDecorator(dateBeginKey, {})(<span></span>)}
            {getFieldDecorator(dateEndKey, {})(<span></span>)} */}
            <div style={{ width: '50%' }}>
              {getFieldDecorator(
                yearKey,
                initialValueYear
                  ? {
                      initialValue: moment(initialValueYear),
                      rules: !!rules ? rules[0] : [],
                    }
                  : { rules: !!rules ? rules[0] : [] },
              )(
                <DatePicker
                  className={theme}
                  mode='year'
                  open={isopen}
                  placeholder={placeholder}
                  format={yearFormat}
                  onPanelChange={this.handlePanelChange}
                  onOpenChange={this.handleOpenChange}
                  onChange={this.clearTime}
                  disabledDate={this.disabledDate}
                  allowClear={true}
                  disabled={disabled}
                />,
              )}
            </div>
            <div style={{ width: '50%', marginLeft: '10px' }}>
              {getFieldDecorator(
                quarterKey,
                initialValueQuarter
                  ? {
                      initialValue: initialValueQuarter,
                      rules: !!rules ? rules[1] : [],
                    }
                  : { rules: !!rules ? rules[1] : [] },
              )(
                <Select
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  style={{ width: '100%' }}
                  disabled={!this.props.form.getFieldValue(yearKey) || disabled}
                  allowClear={true}
                  onChange={this.handleQuarterChange}
                >
                  {quarters.map((item = {}) => (
                    <Option value={item.key} key={item.key}>
                      {item.label}
                    </Option>
                  ))}
                </Select>,
              )}
            </div>
          </Col>
        </Row>
      </Form.Item>
    );
  }
}

// props类型
SimpleQuarterC.propsTypes = {
  form: PropTypes.object, // form对象
  title: PropTypes.string, // 显示名称
  dataIndex: PropTypes.string, // Form识别的Item ID
  initialValueYear: PropTypes.string, // 年默认值，如果需要初始化年和季度，则年和季度均必填。
  initialValueQuarter: PropTypes.string, // 季度默认值
  placeholder: PropTypes.string, // 占位符
  helper: PropTypes.oneOfType([
    // 提示帮助信息
    PropTypes.string,
    PropTypes.element,
  ]),
  rules: PropTypes.array, // 校验规则
  onRef: PropTypes.func, // 本组件的引用（可用来父组件调用内部方法）
  yearKey: PropTypes.string, //用于标识年份的key
  quarterKey: PropTypes.string, //用于标识季度的key
  dateBeginKey: PropTypes.string, //用于标识所选报告开始时间的key
  dateEndKey: PropTypes.string, //用于标识所选报告结束时间的key
  onQuarterChange: PropTypes.func, // 季度变化时调用 返回格式({beginDate:xxxxx,endDate:xxxx})
};

export default SimpleQuarterC;
